package com.xdf.xzymanagementsystem.service.impl;

import com.xdf.xzymanagementsystem.entity.WechatTmpMsg;
import com.xdf.xzymanagementsystem.entity.WechatTmpMsgMetaData;
import com.xdf.xzymanagementsystem.service.CallProcedureService;
import com.xdf.xzymanagementsystem.service.LeakService;
import com.xdf.xzymanagementsystem.util.DatetimeUtils;
import com.xdf.xzymanagementsystem.util.HttpUtils;
import com.xdf.xzymanagementsystem.util.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LeakServiceImpl implements LeakService {

    @Value(value="${globalv.server}")
    private String server;
    @Autowired
    private CallProcedureService callProcedureService;
    @Autowired
    private HttpUtils httpUtils;

    private WechatTmpMsg alarmTmpMsg = new WechatTmpMsg();
    @Autowired
    private MailUtils mailUtils;
    @Autowired
    private LeakService leakService;

    private static final String TMPMSG_URL = "https://www.jzy.world/wxbe/tmpmsg/w";
    private static final String TMPMSG_TMPID = "-WKpM0SjHnBVK2v7qIldtsTfyghLxDbGOyLeAhW7mbM";
    private static final String TMPMSG_OPENID = "oSIC351QqfdfWys65MbOEj4eGU94";

    @Value("${globalv.receivemail}")
    private String receiveMail;

    /**
     * 传入字符串集合，返回推送微信模板消息的对象
     * @param msg 消息内容构成的集合，只有4个
     * @return
     */
    private WechatTmpMsg buildAlarmTmpMsg(List<String> msg){
        if( msg == null || msg.size()<=0 ) throw new RuntimeException("推送报警消息时没有设置内容！");

        if( alarmTmpMsg == null )
            alarmTmpMsg = new WechatTmpMsg();

        // 设置推送消息用到的模板，本模板只有4个元素
        alarmTmpMsg.setTemplateId(TMPMSG_TMPID);

        // 设置推送给的目标微信用户
        List<String> openidList = new ArrayList<>();
        openidList.add(TMPMSG_OPENID);
        alarmTmpMsg.setOpenidList(openidList);

        // 设置推送的内容。循环构建消息体对象
        List<WechatTmpMsgMetaData> metaDataList = new ArrayList<>();
        msg.set(0,"旭纸业 - " + msg.get(0));
        for(String metaSting:msg){
            WechatTmpMsgMetaData metaData = new WechatTmpMsgMetaData(metaSting);
            metaDataList.add(metaData);
        }
        alarmTmpMsg.setMetaList(metaDataList);

        return alarmTmpMsg;
    }

    @Override
    public String checkDeliveryListNoPrice() {
        List<Long> list = callProcedureService.getDeliveryListNoPrice();
        if( list == null || list.size()<=0 ) return "";

        List<String> msg = new ArrayList<>();
        msg.add("检测出货一览表存在无单价的异常数据共" + list.size() + "条");
        msg.add("使用存储过程 usp_deliveryListNoPrice 检查详细数据");
        msg.add(getNowString());
        msg.add("");
        msg.add("");
        msg.add("");
        msg.add("");
        msg.add("");

        // 2021年9月5日 12:46:38 chanchaw
        // 由于未知原因导致的推送微信模板消息接收不到，此时添加发送邮件提醒
        String mailContent = "检测出货一览表存在无单价的异常数据共" + list.size() + "条\n使用存储过程 usp_deliveryListNoPrice 检查详细数据";
        leakService.sendMail4Price(mailContent);

        WechatTmpMsg tmpMsg = buildAlarmTmpMsg(msg);
        return pushWechatTmpMsg(tmpMsg);
    }

    @Override
    public String checkDeliveryList2Price() {
        List<Long> list = callProcedureService.getDeliveryList2Price();
        if( list == null || list.size()<=0 ) return "";

        List<String> msg = new ArrayList<>();
        msg.add("检测出货一览表存在双单价的异常数据共" + list.size() +"条");
        msg.add("使用存储过程 usp_deliveryList2Price 检查详细数据");
        msg.add(getNowString());
        msg.add("");
        msg.add("");
        msg.add("");
        msg.add("");
        msg.add("");

        // 2021年9月5日 12:46:38 chanchaw
        // 由于未知原因导致的推送微信模板消息接收不到，此时添加发送邮件提醒
        String mailContent = "检测出货一览表存在双单价的异常数据共" + list.size() + "条\n使用存储过程 usp_deliveryList2Price 检查详细数据";
        leakService.sendMail4Price(mailContent);

        WechatTmpMsg tmpMsg = buildAlarmTmpMsg(msg);
        return pushWechatTmpMsg(tmpMsg);
    }

    // 推送微信模板消息
    private String pushWechatTmpMsg(WechatTmpMsg msg){
        String ret = "";
        try {
            ret = httpUtils.postJson(TMPMSG_URL,msg);
        } catch (Exception e) {
            throw new RuntimeException("发送模板消息时出现异常！");
        }

        return ret;
    }

    public String pushWechatTmpMsg(List<String> msgList){
        // 向 msgList 后面追加空字符串，使其容量达到8
        if( msgList.size()<8 ) {
            int diff = 8 - msgList.size();
            for(int i = 0;i < diff;i++){
                msgList.add("");
            }
        }
        WechatTmpMsg tmpMsg = buildAlarmTmpMsg(msgList);
        return pushWechatTmpMsg(tmpMsg);
    }

    @Override
    public List<Long> getDeliveryListNoPrice() {
        return callProcedureService.getDeliveryListNoPrice();
    }

    @Override
    public List<Long> getDeliveryList2Price() {
        return callProcedureService.getDeliveryList2Price();
    }

    // 返回当前时间的字符串类型数据
    private String getNowString(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    @Override
    public Boolean sendMail4Price(String content){
        mailUtils.sendSimpleMail(receiveMail,"单价不一致报警",content);
        return true;
    }

    @Override
    public Boolean sendMail(String title, String content) {
        mailUtils.sendSimpleMail(receiveMail,title,content);
        return null;
    }

    @Override
    public String pushStartedMsg(){
        ArrayList<String> msg = new ArrayList<>();
        msg.add("旭纸业企业管理系统");
        msg.add(server + ".xms系统启动完毕");
        msg.add(DatetimeUtils.formatNow());
        return pushWechatTmpMsg(msg);
    }
}

